package com.bidevalution.controller.api;

import com.bidevalution.business.service.BeReplyEnrollService;
import com.bidevalution.business.service.BeReplyTitleService;
import com.bidevalution.dao.entity.BeReplyEnroll;
import com.bidevalution.dao.entity.BeReplyTitle;
import com.bidevalution.support.context.TencentApiConfig;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.google.common.collect.Maps;
import com.qtp.common.core.ContextHolderUtils;
import com.qtp.core.model.Paging;
import com.qtp.core.model.Response;
import com.qtp.core.redis.RedisUtil;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.OConvertUtils;
import com.qtp.core.util.ParamsUtil;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: xiayf
 * @date: 2019-06-11 16:30
 * 操作答辩单位信息控制层
 */
@Log4j2
@RestController
@RequestMapping("/beReplyEnroll")
public class BeReplyEnrollController extends BaseController {

    @Autowired
    private BeReplyEnrollService beReplyEnrollService;
    @Autowired
    private BeReplyTitleService beReplyTitleService;
    @Autowired
	private EnterPriseInfoDubboService enterPriseInfoDubboService;
    @Value("${SystemIdentify}")
	private String appKey;
    /**
     * 获取答辩信息列表
     */
    @RequestMapping(value = "/selectReplyEnrollList", method = RequestMethod.POST)
    @ResponseBody
    public void selectReplyEnrollList(HttpServletRequest request, HttpServletResponse response) {
        setHttpServletResponse(response);
        try {
            //获取请求中的参数
            Map<String, Object> paramsMap = ParamsUtil.getParamsObjValue(request, "replyId,page,rp");
            Paging<List<BeReplyEnroll>> btnResponse = beReplyEnrollService.selectReplyEnrollList(paramsMap);
            long total = btnResponse.getTotal();
            ContextHolderUtils.outGridJson(response, btnResponse.getData(), total, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            //log.error(e.getMessage());
        }
    }
    @RequestMapping(value = "/selectReply", method = RequestMethod.GET)
    @ResponseBody
    public Response<Map<String, Object>> selectReply(@RequestParam("sectionId")String sectionId) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            //获取请求中的参数
        	Map<String, Object> params = new HashMap<>();

			params.put("ep_guid", getTSUser().getOrgId());
			Map<String, Object> enterpriseMap = (Map<String, Object>) enterPriseInfoDubboService.getEnterInfo(params).getResult();
	
			if(enterpriseMap == null) {
				return Response.fail(null);
			}
			List<BeReplyEnroll> dataList = beReplyEnrollService.selectByEnterpriseCode(String.valueOf(enterpriseMap.get("ep_org_code")),sectionId);
			if(dataList.size() > 0) {
				BeReplyEnroll beReplyEnroll = dataList.get(0);
				dataMap.put("card",beReplyEnroll.getLeaderCard());
				dataMap.put("name",beReplyEnroll.getLeaderName());
				dataMap.put("replyEnrollId",beReplyEnroll.getSeqId());
                dataMap.put("replyId",beReplyEnroll.getReplyId());
				BeReplyTitle beReplyTitle = beReplyTitleService.selectByPrimaryKey(beReplyEnroll.getReplyId());

				if(StringUtils.isEmpty(beReplyEnroll.getFaceFileId()) && ((beReplyTitle.getSendTime().getTime()+60L*1000*beReplyTitle.getIdentityTimeSetting()))<=new Date().getTime()) {
					return Response.fail("身份认证时间已过，不允许再进行答辩！");
				}
				return Response.ok(dataMap);
			}
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
        }
        return Response.fail(null);
    }
    @RequestMapping(value = "/selectReplyEnroll", method = RequestMethod.GET)
    @ResponseBody
    public Response<Map<String, Object>> selectReplyEnroll(@RequestParam("replyEnrollId")String replyEnrollId) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            //获取请求中的参数
        	BeReplyEnroll beReplyEnroll = beReplyEnrollService.selectById(replyEnrollId);
			BeReplyTitle beReplyTitle = beReplyTitleService.selectByPrimaryKey(beReplyEnroll.getReplyId());
			if(beReplyTitle.getSendTime() == null) {
				return Response.ok(null);
			}
			dataMap.put("sendTime", beReplyTitle.getSendTime().getTime());
			dataMap.put("sendTimeStr", DateUtil.dateToString(beReplyTitle.getSendTime(), "yyyy-MM-dd HH:mm:ss"));
			dataMap.put("question",beReplyTitle.getQuestion());
			dataMap.put("privateMapKey",TencentApiConfig.tencentApiPrivatekey);
			dataMap.put("sdkAppid",TencentApiConfig.tencentApiSdkAppid);
			dataMap.put("roomId",beReplyEnroll.getReplyOrder());
			dataMap.put("replyTimeSetting",beReplyTitle.getReplyTimeSetting());
			dataMap.put("identityTimeSetting",beReplyTitle.getIdentityTimeSetting());
			dataMap.put("faceFileId",beReplyEnroll.getFaceFileId());
			dataMap.put("userId",appKey + "_" + getTSUser().getUserGuid());
			GenTLSSignatureResult result = tls_sigature.GenTLSSignatureEx(
					TencentApiConfig.tencentApiSdkAppid, appKey + "_" + getTSUser().getUserGuid(),
					TencentApiConfig.tencentApiPrivatekey);
			dataMap.put("userSig",result.urlSig);
			return Response.ok(dataMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.fail(null);
    }
    @RequestMapping(value = "/selectCountByReplyId", method = RequestMethod.GET)
    @ResponseBody
    public Response<Long> selectCountByReplyId(@RequestParam("replyEnrollId")String replyEnrollId) {
        try {
        	BeReplyEnroll beReplyEnroll = beReplyEnrollService.selectById(replyEnrollId);
        	String replyId = beReplyEnroll.getReplyId();
        	long cnt = beReplyEnrollService.selectCountByReplyId(replyId);
        	if(cnt == 0) {
        		RedisUtil.set(replyId+"-face_time", String.valueOf(new Date().getTime()));
        		RedisUtil.expire(replyId+"-face_time",7200);
        	}
        	return Response.ok(cnt);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.fail(null);
    }

    /**
     * 获取投标单位认证提前完成时间
     *
     * @return
     */
    @RequestMapping(value = "/getFaceTime", method = RequestMethod.GET)
    @ResponseBody
    public Response<String> getFaceTime(@RequestParam("replyId") String replyId) {
        try {
            return Response.ok(RedisUtil.get(replyId+"-face_time"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.fail(null);
    }

    @RequestMapping(value = "/updateFinishReply", method = RequestMethod.POST)
    @ResponseBody
    public Response<String> updateReplyEnroll(@RequestParam("replyEnrollId")String replyEnrollId) {
        try {
        	BeReplyEnroll beReplyEnroll = beReplyEnrollService.selectById(replyEnrollId);
        	beReplyEnroll.setIsPublish("Y");
        	beReplyEnroll.setStreamId("49541_"+DigestUtils.md5DigestAsHex((beReplyEnroll.getReplyOrder()+"_"+appKey+"_"+getTSUser().getUserGuid()+"_main").getBytes()));
        	beReplyEnrollService.updateIdentity(beReplyEnroll);
        	return Response.ok(beReplyEnroll.getStreamId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Response.fail(null);
    }

    /**
     * 获取答辩信息列表
     */
    @RequestMapping(value = "/getIdentityEnrollList", method = RequestMethod.GET)
    @ResponseBody
    public Response<List<BeReplyEnroll>> getIdentityEnrollList(HttpServletRequest request, HttpServletResponse response) {
        setHttpServletResponse(response);
        try {
            //获取请求中的参数
            Map<String, Object> paramsMap = ParamsUtil.getParamsObjValue(request, "replyId");
            return Response.ok(beReplyEnrollService.getIdentityEnrollList(OConvertUtils.getString(paramsMap.get("replyId"))));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("获取单位信息列表失败");
        }
    }

    /**
     * 获取投标单位答辩结果
     */
    @RequestMapping(value = "/getBeReplyEnroll", method = RequestMethod.GET)
    @ResponseBody
    public Response<BeReplyEnroll> getBeReplyEnroll(@RequestParam("seqId") String seqId) {
        try {
            return Response.ok(beReplyEnrollService.selectByPrimaryKey(seqId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("获取单位信息失败");
        }
    }

    /**
     * 查询某个题目某个状态的投标单位家数
     *
     * @param replyId
     * @param isPublish
     * @return
     */
    @RequestMapping(value = "/getCountByIsPublish", method = RequestMethod.GET)
    @ResponseBody
    public Response<Map<String, String>> getCountByIsPublish(@RequestParam("replyId") String replyId, @RequestParam("isPublish") String isPublish) {
        Map<String, String> dataMap = Maps.newHashMap();
        try {
            int count = beReplyEnrollService.getCountByIsPublish(replyId, isPublish);
            Date datetime = DateUtil.now();
            String dateStr = DateUtil.dateToString(datetime, DateUtil.PT2);
            dataMap.put("count", String.valueOf(count));
            dataMap.put("dateStr", String.valueOf(dateStr));
            return Response.ok(dataMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("系统错误，请联系管理员！");
        }
    }

    /**
     * 查询某个题目投标单位还没身份认证的家数
     *
     * @param replyId
     * @return
     */
    @RequestMapping(value = "/getCountNotIdentity", method = RequestMethod.GET)
    @ResponseBody
    public Response<Long> getCountNotIdentity(@RequestParam("replyId") String replyId) {
        try {
            return Response.ok(beReplyEnrollService.selectCountByReplyId(replyId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("系统错误，请联系管理员！");
        }
    }
}
